<template>
  <el-dialog
    v-model="show"
    :title="formData.id ? '编辑菜单' : '添加菜单'"
    @close="handleClose"
    width="520px"
    class="menu-dialog"
  >
    <el-form :model="formData" label-width="110px" class="menu-form" size="large">
      <el-form-item label="菜单类型" class="form-item">
        <el-radio-group v-model="formData.type" class="type-radio-group">
          <el-radio :label="0" class="radio-item">
            <div class="option-item">
              <el-icon class="option-icon"><Folder /></el-icon>
              <span>目录</span>
            </div>
          </el-radio>
          <el-radio :label="1" class="radio-item">
            <div class="option-item">
              <el-icon class="option-icon"><Document /></el-icon>
              <span>菜单</span>
            </div>
          </el-radio>
          <el-radio :label="2" class="radio-item">
            <div class="option-item">
              <el-icon class="option-icon"><Pointer /></el-icon>
              <span>按钮</span>
            </div>
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="上级目录" v-if="formData.type !== 0" class="form-item">
        <el-select
          v-model="formData.parent_id"
          placeholder="请选择上级目录"
          class="parent-select"
          clearable
        >
          <el-option :value="0" label="顶级目录">
            <div class="option-item">
              <el-icon class="option-icon"><Top /></el-icon>
              <span>顶级目录</span>
            </div>
          </el-option>
          <el-option
            v-for="item in parentLists"
            :key="item.id"
            :label="item.name"
            :value="item.id"
            :disabled="item.id === formData.id"
          >
            <div class="option-item">
              <el-icon class="option-icon"><FolderOpened /></el-icon>
              <span>{{ item.name }}</span>
            </div>
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="菜单名称" class="form-item">
        <el-input v-model="formData.name" placeholder="请输入菜单名称" class="name-input">
          <template #prefix>
            <el-icon><EditPen /></el-icon>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item label="是否显示" class="form-item" v-if="formData.type == 1">
        <el-select
          v-model="formData.show_type"
          placeholder="请选择显示方式"
          class="show-type-select"
        >
          <el-option :value="1" label="显示">
            <div class="option-item">
              <el-icon class="option-icon"><View /></el-icon>
              <span>显示在左侧菜单</span>
            </div>
          </el-option>
          <el-option :value="2" label="隐藏">
            <div class="option-item">
              <el-icon class="option-icon"><Hide /></el-icon>
              <span>仅视图显示</span>
            </div>
          </el-option>
        </el-select>
        <div class="form-tip">
          <el-icon><InfoFilled /></el-icon>
          <span>选择隐藏则路由将不会出现在侧边栏，但仍然可以访问</span>
        </div>
      </el-form-item>

      <el-form-item label="菜单路径" v-if="formData.type !== 2" class="form-item">
        <el-input v-model="formData.path" placeholder="请输入菜单路径" class="path-input">
          <template #prefix>
            <el-icon><Link /></el-icon>
          </template>
        </el-input>
        <div class="form-tip">
          <el-icon><Warning /></el-icon>
          <span>目录需要加/前缀，其他选项前面不要加/</span>
        </div>
      </el-form-item>

      <el-form-item label="前端组件" v-if="formData.type === 1" class="form-item">
        <el-input
          v-model="formData.component"
          placeholder="请输入前端组件路径"
          class="component-input"
        >
          <template #prefix>
            <el-icon><Document /></el-icon>
          </template>
        </el-input>
        <div class="form-tip">
          <el-icon><Lightning /></el-icon>
          <span>例如: company/lists/index，前面不要加/</span>
        </div>
      </el-form-item>
      <el-form-item label="菜单参数" v-if="formData.type === 1" class="form-item">
        <el-input v-model="formData.query" placeholder="请输入菜单参数" class="params-input">
          <template #prefix>
            <el-icon><EditPen /></el-icon>
          </template>
        </el-input>
        <div class="form-tip">
          <el-icon><Edit /></el-icon>
          <span>格式：?yy1=xx1&yy2=xx2</span>
        </div>
      </el-form-item>
      <el-form-item label="菜单图标" v-if="formData.type !== 2" class="form-item">
        <el-input v-model="formData.icon" placeholder="请输入图标名称" class="icon-input">
          <template #prefix>
            <el-icon><Picture /></el-icon>
          </template>
        </el-input>
        <div class="form-tip">
          <el-icon><Collection /></el-icon>
          <span>使用 ElementPlus icon 组件库中的图标名称</span>
        </div>
      </el-form-item>

      <el-form-item label="权限标识" v-if="formData.type === 2" class="form-item">
        <el-input
          v-model="formData.permission"
          placeholder="请输入权限标识"
          class="permission-input"
        >
          <template #prefix>
            <el-icon><Key /></el-icon>
          </template>
        </el-input>
        <div class="form-tip">
          <el-icon><Lock /></el-icon>
          <span>例如: system:user:add</span>
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose" class="cancel-btn">
          <el-icon><CircleClose /></el-icon>
          取消
        </el-button>
        <el-button type="primary" @click="handleSubmit" class="submit-btn" :loading="submitting">
          <el-icon><CircleCheck /></el-icon>
          {{ formData.id ? '更新菜单' : '创建菜单' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { updateMenuApi, getParentMenuListApi } from '@/api/auth'
import { ElMessage } from 'element-plus'
import {
  Folder,
  Document,
  Pointer,
  Top,
  FolderOpened,
  EditPen,
  View,
  Hide,
  Link,
  Picture,
  Key,
  CircleClose,
  CircleCheck,
  InfoFilled,
  Warning,
  Lightning,
  Collection,
  Lock,
} from '@element-plus/icons-vue'

const show = ref(false)
const submitting = ref(false)
const emit = defineEmits(['success'])

const formData = ref<any>({
  id: 0,
  type: 0,
  parent_id: 0,
  name: '',
  path: '',
  component: '',
  icon: '',
  permission: '',
  show_type: 1,
  query: '',
})

const handleClose = () => {
  show.value = false
  // 重置表单
  formData.value = {
    id: 0,
    type: 0,
    parent_id: 0,
    name: '',
    path: '',
    component: '',
    icon: '',
    permission: '',
    show_type: 1,
  }
}

const handleSubmit = async () => {
  // 表单验证
  if (!formData.value.name?.trim()) {
    ElMessage.error('请输入菜单名称')
    return
  }

  if (formData.value.type !== 2 && !formData.value.path?.trim()) {
    ElMessage.error('请输入菜单路径')
    return
  }

  // 父级菜单不能选择自身
  if (formData.value.id && formData.value.parent_id === formData.value.id) {
    ElMessage.error('父级菜单不能选择自身')
    return
  }

  submitting.value = true
  try {
    const res: any = await updateMenuApi(formData.value)
    ElMessage.success(res.message)
    handleClose()
    emit('success')
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  } finally {
    submitting.value = false
  }
}

// 获取上级菜单
interface MenuItem {
  id: number | string
  name: string
}

const parentLists = ref<MenuItem[]>([])
const getParentMenuList = async () => {
  try {
    const res = await getParentMenuListApi({ status: 1 })
    parentLists.value = res.data
  } catch (error) {
    console.error('获取上级菜单失败:', error)
    ElMessage.error('获取上级菜单失败')
  }
}

const getDetails = (data: any) => {
  if (data) {
    Object.keys(data).forEach((key) => {
      formData.value[key] = data[key]
    })
  } else {
    // 重置为默认值
    formData.value = {
      id: 0,
      type: 0,
      parent_id: 0,
      name: '',
      path: '',
      component: '',
      icon: '',
      permission: '',
      show_type: 1,
    }
  }
}

defineExpose({
  open() {
    show.value = true
  },
  setFormData(data: any) {
    getDetails(data)
  },
  getParentMenuList() {
    getParentMenuList()
  },
})
</script>

<style scoped>
.menu-dialog {
  border-radius: 12px;
}

.menu-dialog :deep(.el-dialog__header) {
  margin: 0;
  padding: 20px 24px;
  border-bottom: 1px solid #f0f0f0;
}

.menu-dialog :deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.menu-dialog :deep(.el-dialog__body) {
  padding: 24px;
}

.menu-form {
  max-width: 100%;
}

.form-item {
  margin-bottom: 20px;
}

.form-item :deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

.type-select,
.parent-select,
.name-input,
.show-type-select,
.path-input,
.component-input,
.icon-input,
.permission-input {
  width: 100%;
}

.option-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 0;
}

.option-icon {
  font-size: 16px;
  color: #909399;
}

.form-tip {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-top: 6px;
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
}

.form-tip .el-icon {
  font-size: 14px;
}

.dialog-footer {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  padding: 16px 24px;
  border-top: 1px solid #f0f0f0;
}

.cancel-btn,
.submit-btn {
  padding: 8px 20px;
  border-radius: 6px;
  font-weight: 500;
}

.cancel-btn .el-icon,
.submit-btn .el-icon {
  margin-right: 4px;
}

/* 响应式设计 */
@media screen and (max-width: 768px) {
  .menu-dialog {
    width: 90% !important;
    margin: 0 auto;
  }

  .menu-dialog :deep(.el-dialog__body) {
    padding: 16px;
  }

  .dialog-footer {
    flex-direction: column;
    gap: 8px;
  }

  .cancel-btn,
  .submit-btn {
    width: 100%;
  }
}
</style>
